# 使用disk_cache 进行知识库管理
import os.path

from diskcache import  Cache

from utils.commont_util import get_know_path, md5_encrypt
import  shortuuid

class KnowledgeManager:
    def __init__(self,know_name,know_path=None):
        # 根据知识库名字 生成知识库id
        # 获取当前知识库路径 如果没有传入。 就默认
        self.know_name=know_name
        self.know_cache = None
        if know_path:
            self.know_path = know_path
        else:
            self.know_path = get_know_path()
        # 根据知识库名字 生成id  名字可以重名否？ 默认不能重名
        # self.know_id = shortuuid.uuid(know_name)
        if self.know_cache is None:
            self.know_cache = Cache(str(os.path.join(self.know_path,self.know_name)))


    def add_knowledge(self,text):
        if self.know_cache is None:
            self.know_cache = Cache(str(os.path.join(self.know_path,self.know_name)))

        text_id=md5_encrypt(text,True)
        print(text_id)
        self.know_cache.set(str(text_id),text)
        return str(text_id)



    def remove_knowledge(self, text):
        # 从知识库中移除知识
        text_id = md5_encrypt(text, True)
        self.know_cache.delete(text_id)
        self.know_cache.delete(text)


    def update_knowledge(self, text_id,new_knowledge):
        self.know_cache.set(text_id,new_knowledge)


    def get_knowledge(self, knowledge_id):
        # 从知识库中获取知识
        return self.know_cache.get(str(knowledge_id))


    def get_all_know(self):
        keys = self.know_cache.iterkeys()
        return [ self.get_knowledge(key) for key in keys]

    def query_know(self,txt,top_k=10):
        # 开始进行文本检索
        pass

if __name__ == '__main__':
    s=KnowledgeManager("abc")
    print(s)